<?php

class Talktangle_Model_DbTable_Followers extends Engine_Db_Table
{
    protected $_rowClass = 'Talktangle_Model_Follower';

    public function getFollowerIds($user_id = 0){
        if(empty($user_id)) {
            $user = Engine_Api::_()->user()->getViewer();
            if($user) $user_id = $user->user_id;
        }
        if(empty($user_id)) return array();
        
        $select = $this->select()
                       ->where('object_id = ?',$user_id)
                       ->from($this->info('name'),array('owner_id'));
        $rows = $this->fetchAll($select);
        
        $result = array();
        foreach($rows as $row){
            $result[] = $row->owner_id;
        }
        
        return $result;
    }
    
    public function getSubscriber($user_id = 0) {
        if(empty($user_id)) {
            $user = Engine_Api::_()->user()->getViewer();
            if($user) $user_id = $user->user_id;
        }
        if(empty($user_id)) return array();
        
        $select = $this->select()
                       ->where('owner_id = ?',$user_id)
                       ->from($this->info('name'),array('object_id'));
        $rows = $this->fetchAll($select);
        
        $result = array();
        foreach($rows as $row){
            $result[] = $row->object_id;
        }
        
        return $result;
    }
    public function isFollower($owner_id,$user_id){
        $select = $this->select()
                       ->where('owner_id = ?',$owner_id)
                       ->where('object_id = ?',$user_id);
        $row = $this->fetchRow($select);
        
        if($row && $row->getIdentity()) return true;
        return false;
                       
    }
    
    public function getFollower($owner_id,$user_id){
        $select = $this->select()
                       ->where('owner_id = ?',$owner_id)
                       ->where('object_id = ?',$user_id);
        $row = $this->fetchRow($select);
        return $row;
    }
    

    public function addFollower($owner_id,$user_id){
        $row = $this->getFollower($owner_id,$user_id);
        if($row && !$row->getIdentity()) return $row;
        
        $row = $this->createRow();
        $row->owner_id = $owner_id;
        $row->object_id = $user_id;
        $row->object_type ='user';
        $row->save();
        return $row;
    }
    
    public function unFollower($owner_id,$user_id){
        $this->delete(" owner_id = $owner_id and object_id = $user_id ");
    }
}